package com.ai.nsa.utils.page.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 抽象页
 *
 * @author Feng Chen 2017/6/17.
 */
public abstract class AbstractPage<T> implements Page<T> {

    protected int pageSize;

    protected int totalPage;

    protected int totalCount;

    protected List<T> rows;

    protected Map<Integer, List<T>> pages;

    public AbstractPage(List<T> rows, int pageSize) {
        this.pageSize = pageSize;
        this.rows = rows;
        pages = new HashMap<Integer, List<T>>();

        page();
    }

    private synchronized void page() {

        // 没数据
        if (rows == null || rows.isEmpty()) {
            totalPage = 0;
            totalCount = 0;
            return;
        }

        // 计算总条数
        totalCount = rows.size();

        // 计算总页数
        totalPage = (int) Math.ceil((rows.size() * 1.0) / pageSize);

        // 计算页数据
        for (int n = 1; n <= totalPage; n++) {
            List<T> page = new ArrayList<T>();
            for (int s = ((n - 1) * pageSize); (s <= (n * pageSize - 1) && s < rows.size()); s++) {
                page.add(rows.get(s));
            }
            pages.put(n, page);
        }

    }


}
